﻿///<reference path="../ext/vswd-ext_2.0.2.js" />

function doLayout() {
    north = {
        region: 'north',
        xtype: 'toolbar',
        height: 30,
        items: [toolbarItems]
    };

    center = {
        id: 'mapPanel',
        region: 'center',
        xtype: 'panel',
        layout: 'accordion'
    };

    west = { region: 'west',
        xtype: 'panel',
        id: 'leftAccordionPanel',
        layout: 'accordion',
        animate: true,
        split: true,
        collapsible: true,
        title: '功能目录',
        width: 180,
        bbar: coordinateBar,
        items: accordionItems
    };

    south = {
        region: 'south',
        xtype: 'panel',
        height: 27,
        bbar: statusBar
    };

    mapLayout = new Ext.Viewport({
        id: "main",
        layout: "border", // 边框布局
        items: [north, center, west, south],
        renderTo: Ext.getBody()
    });
}

function initBaseMap() {
    dojo.require("esri.map");
    dojo.require('esri.tasks.geometry');
    dojo.require('esri.tasks.query');
    dojo.require("esri.toolbars.navigation");
    dojo.require("esri.toolbars.draw");
    
    //获得地图的panel
    var initExtent = new esri.geometry.Extent({ "xmin": -16008971.204045713, "ymin": 2515961.12479618, "xmax": -5412964.595044257, "ymax": 8347189.138614156, "spatialReference": { "wkid": 102100} });
    map = new esri.Map(Ext.getCmp('mapPanel').body.dom, { extent: initExtent });
    navToolbar = new esri.toolbars.Navigation(map);
    drawToolbar = new esri.toolbars.Draw(map);
    dojo.connect(map, "onLoad", function() { /*debugger;*/ });
    dojo.connect(map, "onExtentChange", function() { });
    dojo.connect(map, "onMouseMove", function(evt) {
        var mp = esri.geometry.webMercatorToGeographic(evt.mapPoint);
        coordinateBar.setText('经度：' + formatLL(mp.x, '#.##') + "，纬度：" + formatLL(mp.y, '#.##'));
        //        var pt = evt.mapPoint;
        //        Ext.Ajax.request({
        //            url: "proxy.ashx" + '?' + 'http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer/project?f=json&inSR=' + pt.spatialReference.wkid + '&outSR=4326&geometries={"geometryType":"esriGeometryPoint","geometries":[{"x":' + pt.x + ',"y":' + pt.y + '}]}',
        //            success: function(response, scope) { var p = Ext.decode(response.responseText); coordinateBar.setText('经度：' + formatLL(p.geometries[0].x, '#.##') + "，纬度：" + formatLL(p.geometries[0].y, '#.##')); },
        //            failure: function() { }
        //        });
        //        var gsvc = new esri.tasks.GeometryService('http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer');
        //        gsvc.onProjectComplete += function() { debugger; }
        //        debugger;
        //        var pt;
        //        gsvc.project([evt.mapPoint], { "wkid": 4326 }, function(projectedPoints) {
        //            debugger;
        //            pt = projectedPoints[0];
        //        }, function() {
        //            debugger;
        //        });
        //        coordinateBar.setText('经度：' + pt.x + "，纬度：" + pt.y);
        //doStuff(evt.mapPoint);
    });

    var basemap = new esri.layers.ArcGISTiledMapServiceLayer("http://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer");
    map.addLayer(basemap);

    //map.addLayer(new esri.layers.ArcGISDynamicMapServiceLayer("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/", { opacity: 0.4 }));
}

function doStuff(pt) {
    //debugger;
    //console.log("dostuff");
    var geoservice = new esri.tasks.GeometryService(esriGeometryService);
    var sourcewkid = new esri.SpatialReference({ "wkid": 102100 });
    var destwkid = new esri.SpatialReference({ "wkid": 4326 });
    var point = new esri.geometry.Point(pt.x, pt.y, sourcewkid);
    console.log(sourcewkid, destwkid, point);
    try {
        geoservice.project([point], destwkid, onProjectComplete, onError);
    }
    catch (err) {
        console.log(err);
    }
    var infoTemplate = new esri.InfoTemplate("Test", "test: ${test}");
    var attr = { "test": "test" };
    var sms = new esri.symbol.SimpleMarkerSymbol().setStyle(
                                esri.symbol.SimpleMarkerSymbol.STYLE_SQUARE).setColor(
                                new dojo.Color([255, 0, 0, 0.5]));
    var test = new esri.Graphic(point, sms, attr, infoTemplate);
    map.graphics.add(test);
}

function onProjectComplete(graphics) {
}

function onError() {
}

function showLoadingMask() {
    esri.show(loading);
    map.disableMapNavigation();
    map.hideZoomSlider();
}

function hideLoadingMask(error) {
    layersLoaded++;
    if (layersLoaded === map.layerIds.length) {
        esri.hide(loading);
        map.enableMapNavigation();
        map.showZoomSlider();
        layersLoaded = 0;
    }
}

function createLayerTree() {
    layerTree = new Ext.tree.TreePanel({
        renderTo: 'treeViewLayers',
        useArrows: true,
        animate: true,
        enableDD: true,
        containerScroll: true,
        rootVisible: false,
        frame: true,
        root: {
            nodeType: 'async'
        },
        dataUrl: 'handler/LayersTree.ashx',
        listeners: {
            'checkchange': addRemoveLayer,
            'contextmenu': function(node) {
                node.select();
                layerTreeContextMenuAGS.show(node.ui.getAnchor());
            },
            'load': prepareTreeGridOptions
        }
    });
}

//This function adds layer to map or removes layer from the map according to its layer type via layer tree checkboxes
function addRemoveLayer(node, checked) {
    layerID = node.attributes.id;
    layType = node.attributes.serviceType;
    if (checked == true) {
        if (layType == 1) { //tile service için		
            tileLayers[layerID] = new GTileLayer(copyrightColl, 0, 21);
            tileLayers[layerID].getTileUrl = function(tile, zoom) {
                return node.attributes.serviceUrl + zoom + '/' + tile.x + '/' + tile.y + '.png';
            };
            tileLayers[layerID].isPng = function() {
                return true;
            };
            tileLayers[layerID].getOpacity = function() {
                return (node.attributes.layerTp / 10);
            }

            mapLayers[layerID] = new Array(2);
            mapLayers[layerID][0] = new GTileLayerOverlay(tileLayers[layerID]);
            mapLayers[layerID][1] = 1; //tile layer
        }
        else if (layType == 2) { //ArcGIS Server Dynamic Service
            var urlText = node.attributes.serviceUrl;
            urlText.search(/MapServer/);
            var mapUrl = urlText.substr(0, urlText.search(/MapServer/) + 9);
            var layID = urlText.substr(urlText.search(/MapServer/) + 10, 1);
            var imageParams = new esri.layers.ImageParameters();
            imageParams.layerIds = [layID];
            imageParams.layerOption = esri.layers.ImageParameters.LAYER_OPTION_SHOW;
            imageParams.transparent = true;
            imageParams.opacity = 0.5;
            
            mapLayers[layerID] = new Array(2);
            mapLayers[layerID][0] = new esri.layers.ArcGISDynamicMapServiceLayer(mapUrl, { "imageParameters": imageParams });
            mapLayers[layerID][1] = 2; //dynamic layer			
        }
        else if (layType == 3) { //ArcGIS Server Tile Service
            var urlText = node.attributes.serviceUrl;
            urlText.search(/MapServer/);
            var mapUrl = urlText.substr(0, urlText.search(/MapServer/) + 9);
            mapLayers[layerID] = new Array(2);
            mapLayers[layerID][0] = new esri.layers.ArcGISTiledMapServiceLayer(mapUrl);
            mapLayers[layerID][1] = 3; //Arcgis tile 				
        }
        else if (layType == 4) { //wms tile layer			

            tileLayers[layerID] = new GTileLayer(copyrightColl, 0, 21);
            tileLayers[layerID].myFormat = 'image/png';
            tileLayers[layerID].myBaseURL = node.attributes.serviceUrl;
            tileLayers[layerID].myVersion = '1.1.1';
            tileLayers[layerID].getTileUrl = CustomGetTileUrl;
            tileLayers[layerID].getOpacity = function() {
                return (node.attributes.layerTp / 10);
            }

            mapLayers[layerID] = new Array(2);
            mapLayers[layerID][0] = new GTileLayerOverlay(tileLayers[layerID]);
            mapLayers[layerID][1] = 4; //wms tile layer
        }
        else if (layType == 5) { //kml-georss service için			
            mapLayers[layerID] = new Array(2);
            mapLayers[layerID][0] = new GGeoXml(node.attributes.serviceUrl);
            mapLayers[layerID][1] = 5; //kml-georss layer			
        }
        map.addLayer(mapLayers[layerID][0]);
    }
    else {
        map.removeLayer(mapLayers[layerID][0]);
    }
}


function prepareTreeGridOptions() {
    layerTree.root.eachChild(function(node, v) {
        var layType = node.attributes.serviceType;
        if (layType == 2 || layType == 3) {
            prepareGridOptions(node.attributes.id, node.attributes.serviceUrl);
        }
    }, null, null);
}

function prepareGridOptions(sentlayerID, layerUrl) {
    var sentlayerx = sentlayerID;
    var fieldAliases;
    var fieldArr = new Array();
    var colArr = new Array();
    var queryArr = new Array();
    var layerExtent; 
    var extentArr = new Array();
    var fieldArrWS = new Array();
    var colArrWS = new Array();
    statusBar.showBusy('Processing - Getting Layer Properties');
    Ext.Ajax.request({
        url: "proxy.ashx" + '?' + layerUrl + '?f=json',
        success: function(result) {
            if (result.responseText != '') {
                var jsonData = Ext.util.JSON.decode(result.responseText);
                fieldAliases = jsonData.fields;
                layerExtent = jsonData.extent;
                esriGeomTypeArr[sentlayerx] = jsonData.geometryType;
                var i = 0;

                for (var key in fieldAliases) {
                    i++;
                    if (fieldAliases[key].name === undefined) { }
                    else {
                        if (fieldAliases[key].name != '') {
                            fieldArr.push('attributes.' + fieldAliases[key].name);
                            queryArr.push([fieldAliases[key].name]);
                            colArr.push({
                                header: fieldAliases[key].name,
                                dataIndex: 'attributes.' + fieldAliases[key].name
                            });

                            var tmpField = fieldAliases[key].name.toString();
                            if (tmpField.search(/shape/i) == -1) {
                                fieldArrWS.push('attributes.' + fieldAliases[key].name);
                                colArrWS.push({
                                    header: fieldAliases[key].name,
                                    dataIndex: 'attributes.' + fieldAliases[key].name
                                });
                            }
                        }
                    }
                }
                debugger;
                extentArr[0] = layerExtent.xmin;
                extentArr[1] = layerExtent.ymin;
                extentArr[2] = layerExtent.xmax;
                extentArr[3] = layerExtent.ymax;
                extentArr[4] = layerExtent.spatialReference.wkid;
            }
            agsLayerFields[sentlayerx] = fieldArr;
            agsLayerColumns[sentlayerx] = colArr;
            agsQueryFields[sentlayerx] = queryArr;
            agsLayerExtents[sentlayerx] = extentArr;
            agsLayerFieldsWS[sentlayerx] = fieldArrWS; //without shapes
            agsLayerColumnsWS[sentlayerx] = colArrWS; //without shapes
            statusBar.clearStatus();
            statusBar.setStatus('Ready');
        },
        failure: function(result) {
            console.log('There is a problem, please try again later!');
        }
    });
}

function zoom2AGSLayer(menuitem, e) {
    var selectedNode = layerTree.selModel.selNode;
    var extent = agsLayerExtents[selectedNode.attributes.id];
    Ext.Ajax.request({
        url: esriGeometryService + '/project?f=json&inSR=' + extent[4] + '&outSR=' + map.extent.spatialReference.wkid + '&geometries=' + '{"geometryType":"esriGeometryPoint","geometries":[{"x":' + extent[0] + ',"y":' + extent[1] + '},{"x":' + extent[2] + ',"y":' + extent[3] + '}]}',
        scriptTag: true,
        success: function(a, b) {
            var t = Ext.decode(a.responseText);
            map.extent.update(t.geometries[0].x, t.geometries[0].y, t.geometries[1].x, t.geometries[1].y, new esri.SpatialReference({ "wkid": 102100 }));
            map.resize();
        },
        failure: function(a, b) { Ext.MessageBox.alert('zoom2AGSLayer error'); }
    });
}

function deleteLayerTreeNode() {

}

function openLayerInfoWindow() {

}

//This function gets the attribute table of selected layer, but the full list cannot be taken from the server
//due to ArcGIS Server's default limitation (500 rows). This function is experimental because loading 500+ rows
//in a data grid make your browser slow.
function getLayerAttributeTable() {
    shapeFieldStatus = false;
    var selectedNode = layerTree.selModel.selNode;
    if (selectedNode != null) {
        var selID = selectedNode.attributes.id;
        if (selectedNode.attributes.serviceType == 2 || selectedNode.attributes.serviceType == 3) {
            statusBar.showBusy('Processing - Getting Attribute');
            var fieldLength = agsQueryFields[selID].length;
            var fields = '';
            for (i = 0; i < fieldLength; i++) {
                var tmpField = agsQueryFields[selID][i].toString();
                if (tmpField.search(/shape/i) == -1) {
                    if (fields == '') fields = agsQueryFields[selID][i];
                    else fields = fields + ',' + agsQueryFields[selID][i];
                }
            }

            var geoText = 'geometry=' + agsLayerExtents[selID][0] + ',' + agsLayerExtents[selID][1] + ',' + agsLayerExtents[selID][2] + ',' + agsLayerExtents[selID][3] + '&geometryType=esriGeometryEnvelope';
            var queryUrl = "proxy.ashx" + '?' + selectedNode.attributes.serviceUrl + '/query?' + geoText + '&returnGeometry=false&outFields=' + fields + '&f=json&outSR=4326';
            lastKMLUrl = selectedNode.attributes.serviceUrl + '/query?' + geoText + '&returnGeometry=true&outFields=*&f=kmz&outSR=4326';
            prepareDataGrid(queryUrl, layerTree.selModel.selNode.attributes.text, selID);
        }
        else {
            Ext.Msg.alert('Alert', 'Layer must be an ArcGIS Server Layer');
        }
    }
    else {
        Ext.Msg.alert('Alert', 'Please select a layer from tree');
    }	
}

function prepareDataGrid(queryUrl, nameLabelValue, selID) {
    var attWindowlayerNameLabel = new Ext.form.TextField({
        id: 'attWindowlayerNameID',
        name: 'attWindowlayerNameName',
        fieldLabel: '图层名',
        width: 230,
        readOnly: true
    });

    attWindowlayerNameLabel.setValue(nameLabelValue);
    
    if (shapeFieldStatus == true)
        var attWindowOptionGridColumns = new Ext.grid.ColumnModel(agsLayerColumns[selID]);
    else
        var attWindowOptionGridColumns = new Ext.grid.ColumnModel(agsLayerColumnsWS[selID]);
    
    if (shapeFieldStatus == true)
        var attWindowFieldDataReader = new Ext.data.JsonReader({ fields: agsLayerFields[selID], root: 'features' });
    else
        var attWindowFieldDataReader = new Ext.data.JsonReader({ fields: agsLayerFieldsWS[selID], root: 'features' });


	var attWindowFieldDataProxy = new Ext.data.HttpProxy({url: queryUrl });

    attWindowFieldDataStore = new Ext.data.Store({
        reader: attWindowFieldDataReader,
        proxy:attWindowFieldDataProxy,
        listeners: {
            load: function() {
                statusBar.clearStatus();
                statusBar.setStatus('Ready - Total Records Fetched : ' + this.getCount());
            }
        }
    });

    //attWindowFieldDataStore.load();
    attWindowGrid = new Ext.grid.GridPanel({
        cm: attWindowOptionGridColumns,
        ds: attWindowFieldDataStore,
        loadMask: true, 
        height: 300
    });

    var attWindowForm = new Ext.form.FormPanel({
        frame: true,
        width: 520,
        height: 340,
        defaults: {
            labelSeparator: ':',
            hideLabel: false
        },
        items: [
            attWindowlayerNameLabel,
            attWindowGrid
        ]
    });

    if (tempWindowItem != null) attributeWindow.remove(tempWindowItem, true);
    tempWindowItem = attributeWindow.insert(0, attWindowForm);

    attributeWindow.setAnimateTarget(Ext.get('animationPoint'));
    //attributeWindow.setAnimateTarget(Ext.getCmp('tbarQueryButton')); 

    if (attributeWindow.isVisible()) {
        attributeWindow.doLayout();
        attributeWindow.focus();
    }
    else {
        attributeWindow.show();
        attributeWindow.focus();
    }

    attWindowFieldDataStore.load();
}

function identify(extent) {
//    dojo.connect(map, "onClick", doIdentify);
//    identifyTask = new esri.tasks.IdentifyTask("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/BloomfieldHillsMichigan/Parcels/MapServer");
    var plt = new esri.geometry.Point(extent.xmin, extent.ymax, extent.spatialReference.wkid);
    var prb = new esri.geometry.Point(extent.xmax, extent.ymin, extent.spatialReference.wkid);

    var minPoint = esri.geometry.webMercatorToGeographic(plt);
    var maxPoint = esri.geometry.webMercatorToGeographic(prb);
    
    //var mp = esri.geometry.webMercatorToGeographic(evt.mapPoint);
    shapeFieldStatus = true;
    var selectedNode = layerTree.selModel.selNode;
    if (selectedNode != null) {
        var selID = selectedNode.attributes.id;
        lastIdentifiedLayerID = selID;
        if (selectedNode.attributes.serviceType == 2 || selectedNode.attributes.serviceType == 3) {
            statusBar.showBusy('Processing - 开始选择');

            var urlTxt = selectedNode.attributes.serviceUrl.substr(0, selectedNode.attributes.serviceUrl.search(/MapServer/) + 9);
            var identifyTask = new esri.tasks.IdentifyTask(urlTxt);
            identifyTask.onComplete = function(results) {
                debugger;
                var sfs = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255, 0, 0]), 3), new dojo.Color([125, 125, 125, 0.35]));
                Ext.each(results, function(result) {
                    debugger;
                    map.graphics.add(new esri.Graphic(result.feature.geometry, sfs));
                });

            } 
            identifyTask.onError = function() { Ext.Msg.alert('identify error'); }
            var identifyParams = new esri.tasks.IdentifyParameters();
            identifyParams.tolerance = 3;
            identifyParams.geometry = minPoint;
            identifyParams.returnGeometry = true;
            identifyParams.layerIds = [3];
            identifyParams.mapExtent = map.extent;
            identifyTask.execute(identifyParams);
            
            
//            geomText = minPoint.y + ',' + minPoint.x + ',' + maxPoint.y + ',' + maxPoint.x;
//            var queryUrl = "proxy.ashx" + '?' + selectedNode.attributes.serviceUrl + '/query%3Fgeometry=' + geomText
//							+ '&geometryType=esriGeometryEnvelope&inSR=4326&spatialRel=esriSpatialRelIntersects&returnGeometry=true&outSR=4326&outFields=*&f=json';

//            lastKMLUrl = selectedNode.attributes.serviceUrl + '/query?geometry=' + geomText + '&geometryType=esriGeometryEnvelope&inSR=4326&spatialRel=esriSpatialRelIntersects&returnGeometry=true&outSR=4326&outFields=*&f=kmz';
//            prepareDataGrid(queryUrl, selectedNode.attributes.text, selID);
        }
        else {
            Ext.Msg.alert('Alert', 'Layer must be an ArcGIS Server Layer');
        }
    }
    else {
        Ext.Msg.alert('Alert', 'Please select a layer from tree');
    }
}